package com.share.lottery.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.conn.util.InetAddressUtils;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;

public class PhoneUtil {

	/**
	 * 屏幕宽度、高度默认
	 */
	public static int DM_WIDTH = 0;
	public static int DM_HEIGHT = 0;

	/**
	 * 
	 * @Description:TODO 获取手机型号
	 * @param@return
	 * @return String
	 * @author yjj
	 * @date 2014-4-22 下午4:23:08
	 */
	public static String getPhoneModel() {
		return android.os.Build.MODEL;
	}

	/**
	 * 
	 * @Description:TODO 获取手机系统版本
	 * @param@return
	 * @return String
	 * @author yjj
	 * @date 2014-4-22 下午4:23:36
	 */
	public static String getPhoneVersion() {
		return android.os.Build.VERSION.RELEASE;
	}

	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public static String getApplicationVersion(Context context) {
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(),
					0);
			String version = info.versionName;
			return version;
		} catch (Exception e) {
			e.printStackTrace();
			return "can_not_find_version_name";
		}
	}

	/**
	 * deviceID的组成为：渠道标志+识别符来源标志+hash后的终端识别符
	 * 
	 * 渠道标志为： 1，andriod（a）
	 * 
	 * 识别符来源标志： 1， wifi mac地址（wifi）； 2， IMEI（imei）； 3， 序列号（sn）； 4，
	 * id：随机码。若前面的都取不到时，则随机生成一个随机码，需要缓存。
	 * 
	 * @param context
	 * @return
	 */
	public static String getDeviceId(Context context) {

		StringBuilder deviceId = new StringBuilder();

		try {

			// wifi mac地址
			WifiManager wifi = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			String wifiMac = info.getMacAddress();
			if (ObjTool.isNotNull(wifiMac)) {
				deviceId.append("mac_");
				deviceId.append(wifiMac);
				return deviceId.toString();
			}

			// IMEI（imei）
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			String imei = tm.getDeviceId();
			if (ObjTool.isNotNull(imei)) {
				deviceId.append("imei_");
				deviceId.append(imei);
				return deviceId.toString();
			}

			// 序列号（sn）
			String sn = tm.getSimSerialNumber();
			if (ObjTool.isNotNull(sn)) {
				deviceId.append("sn_");
				deviceId.append(sn);
				return deviceId.toString();
			}

			// 如果上面都没有， 则生成一个id：随机码
			String uuid = getUUID(context);
			if (ObjTool.isNotNull(uuid)) {
				deviceId.append("id_");
				deviceId.append(uuid);
				return deviceId.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			deviceId.append("id").append(getUUID(context));
		}

		return deviceId.toString();

	}

	/**
	 * 得到全局唯一UUID
	 */
	public static String getUUID(Context context) {
		final TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);

		final String tmDevice, tmSerial, androidId;

		tmDevice = "" + tm.getDeviceId();

		tmSerial = "" + tm.getSimSerialNumber();

		androidId = ""
				+ android.provider.Settings.Secure.getString(
						context.getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);

		UUID deviceUuid = new UUID(androidId.hashCode(),
				((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());

		String uniqueId = deviceUuid.toString();

		return uniqueId;
	}

	/**
	 * 
	 * @Description:TODO获取手机的IP地址
	 * @param@return
	 * @return String IP地址
	 * @author yjj
	 * @date 2014-4-14 上午10:54:23
	 */
	public static String getLocalIpAddress() {
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			while (en.hasMoreElements()) {
				NetworkInterface nif = en.nextElement();
				Enumeration<InetAddress> enumIpAddr = nif.getInetAddresses();
				while (enumIpAddr.hasMoreElements()) {
					InetAddress mInetAddress = enumIpAddr.nextElement();
					if (!mInetAddress.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(mInetAddress
									.getHostAddress())) {
						return mInetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("getLocalIpAddress()", "获取本地IP地址失败");
		}

		return null;
	}

	public static int getDMWidth(Context context) {

		if (DM_WIDTH == 0) {
			DisplayMetrics dm = PhoneUtil.getDisplayMetrics(context);
			DM_WIDTH = dm.widthPixels;
			DM_HEIGHT = dm.heightPixels;
		}
		return DM_WIDTH;
	}

	public static int getDMHeight(Context context) {

		if (DM_HEIGHT == 0) {
			DisplayMetrics dm = PhoneUtil.getDisplayMetrics(context);
			DM_WIDTH = dm.widthPixels;
			DM_HEIGHT = dm.heightPixels;
		}
		return DM_HEIGHT;
	}

	/**
	 * 
	 * @Description: 判断网络是否可用
	 * @param context
	 * @return
	 */
	public static boolean isNetAvaiable(Context context) {
		boolean flag = true;
		ConnectivityManager mag = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = mag.getActiveNetworkInfo();
		if (info == null) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 
	 * 作者: zhuwei 2012-3-12-下午4:49:07
	 * 
	 * @Description: 读取并返回手机的IMEI数据
	 * @param
	 * @return 返回手机的IMEI数据
	 * @throws
	 */
	public String getPhoneIMEI(Context context, TelephonyManager tm) {
		String imei = tm.getDeviceId();
		return imei;
	}

	/**
	 * 
	 * @Description: 获取手机分辨率
	 * @param act
	 * @return
	 */
	public static DisplayMetrics getDisplayMetrics(Context context) {
		DisplayMetrics displaysMetrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(displaysMetrics);
		return displaysMetrics;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 
	 * @Description:TODO检查某个APP是否已经安装
	 * @param context
	 * @param packageName
	 * @return
	 * @return boolean
	 * @author zhuw
	 * @date 2013-5-17 上午11:07:04
	 */
	public static boolean checkApkExist(Context context, String packageName) {
		if (packageName == null || "".equals(packageName))
			return false;
		try {
			ApplicationInfo info = context.getPackageManager()
					.getApplicationInfo(packageName,
							PackageManager.GET_UNINSTALLED_PACKAGES);
			return true;
		} catch (NameNotFoundException e) {
			return false;
		}
	}

	/***
	 * 
	 * @Description:打开另外的Apk程序
	 * @param ctx
	 * @param packageName
	 */
	public static void startApkActivity(final Context ctx, String packageName) {
		PackageManager pm = ctx.getPackageManager();
		PackageInfo pi;
		try {
			pi = pm.getPackageInfo(packageName, 0);
			Intent intent = new Intent(Intent.ACTION_MAIN, null);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setPackage(pi.packageName);

			List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);

			ResolveInfo ri = apps.iterator().next();
			if (ri != null) {
				String className = ri.activityInfo.name;
				intent.setComponent(new ComponentName(packageName, className));
				ctx.startActivity(intent);
			}
		} catch (NameNotFoundException e) {

		}
	}

	/**
	 * make true current connect service is wifi
	 * 
	 * @param mContext
	 * @return
	 */
	public static boolean isWifi(Context mContext) {
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @Description: 调用拨打电话界面
	 * @param num
	 * @param context
	 * @return void
	 * @author lmj
	 * @date 2014-10-8 上午6:11:31
	 */
	public static void doDial(String num, Context context) {
//		Pattern p = Pattern.compile("\\d+?");
//		Matcher match = p.matcher(num);
//		// 正则验证输入的是否为数字
//		if (match.matches()) {
		Uri uri=Uri.parse("tel:"+num);   //拨打电话号码的URI格式
		Intent it=new Intent();   //实例化Intent
		it.setAction(Intent.ACTION_DIAL);   //指定Action

		it.setData(uri);   //设置数据
	}
}
